<template>
  <view
    class="leader-report-complaint bg-white px-3.5 pt-2.5 pb-6.25 box-border"
  >
    <view class="flex flex-row justify-between items-center">
      <view
        :class="
          queryParam.type == 0
            ? 'opt-btn opt-btn-active'
            : 'opt-btn opt-btn-unactive'
        "
        @click="updateEvaluationStat(0)"
        >按月</view
      >
      <view
        :class="
          queryParam.type == 1
            ? 'opt-btn opt-btn-active'
            : 'opt-btn opt-btn-unactive'
        "
        @click="updateEvaluationStat(1)"
        >按年</view
      >
      <view class="select-input" @click="showPicker = true">
        <picker
          mode="date"
          :fields="queryParam.type == 0 ? 'month' : 'year'"
          :value="queryParam.yearMonth"
          @change="bindPickerChange"
          @cancel="showPicker = false"
        >
          <up-input
            v-model="timeStr"
            disabled
            disabledColor="#ffffff"
            placeholder="请选择"
            border="none"
            color="#000000"
            placeholderStyle="{color: '#707070'}"
          >
            <template #suffix>
              <view class="pr-1">
                <up-icon name="arrow-down" color="#000000" size="18"></up-icon>
              </view>
            </template>
          </up-input>
        </picker>
      </view>
    </view>
    <view class="mt-4.25">
      <view class="ring-charts">
        <qiun-data-charts
          type="ring"
          :opts="evaluationChart.opts"
          :chartData="evaluationChart.chartData"
        />
      </view>
    </view>
    <!-- 服务评价趋势 -->
    <view class="mt-4.25" v-if="queryParam.type == 1">
      <text class="text-black text-[32rpx] font-bold">服务评价趋势</text>
      <view class="mt-4 h-[300rpx] bar-chart">
        <qiun-data-charts
          type="column"
          :opts="chartParam.opts"
          tooltipFormat="normalTooltip"
          :chartData="chartParam.chartData"
        />
      </view>
    </view>
    <!-- 社区评价排行 -->
    <view :class="queryParam.type == 0 ? 'mt-4.25' : 'mt-1'">
      <text class="text-black text-[32rpx] font-bold">社区评价排行</text>
      <view class="mt-4">
        <uni-table ref="table" border stripe emptyText="暂无更多数据">
          <uni-tr>
            <uni-th align="center" width="85">社区名称</uni-th>
            <uni-th align="center" width="70">评价总数</uni-th>
            <uni-th align="center" width="50">满意</uni-th>
            <uni-th align="center" width="50">一般</uni-th>
            <uni-th align="center" width="60">不满意</uni-th>
          </uni-tr>
          <uni-tr v-for="(item, index) in tableList" :key="index">
            <uni-td align="center">{{ item.communityName }}</uni-td>
            <uni-td align="center">
              <view class="text-[#038afe]" @click="scanDetail(item)">{{
                item.cmySumCount
              }}</view>
            </uni-td>
            <uni-td align="center">{{ item.cmySatisfiedCount }}</uni-td>
            <uni-td align="center">{{ item.cmyGeneralCount }}</uni-td>
            <uni-td align="center">{{ item.cmyDissatisfiedCount }}</uni-td>
          </uni-tr>
        </uni-table>
      </view>
    </view>
    <up-toast ref="uToastRef"></up-toast>
  </view>
</template>

<script setup lang="ts">
import { evaluationStat } from "@/api/evaluation/index";
import { useUserInfoStore } from "@/stores/userInfo";
import { toFixedWithoutTrailingZeros } from "@/utils/tools";
import dayjs from "dayjs";
const userInfoStore = useUserInfoStore();
const uToastRef = <any>ref(null);

const data = reactive({
  showPicker: false,
  queryParam: {
    type: 0, // 0按月 1按年
    yearMonth: dayjs(new Date()).format("YYYY-MM"),
    policeLeaderId: userInfoStore.userInfo.userId,
    communityId: null,
  },
  timeStr: dayjs(new Date()).format("YYYY年MM月"),
  tableList: <any>[],
});
const { showPicker, queryParam, timeStr, tableList } = toRefs(data);

// 饼状图
const evaluationChart = reactive({
  chartData: {},
  opts: {
    animation: false, // 关闭动画
    update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
    duration: 0, // 关闭动画过度
    rotate: false,
    rotateLock: false,
    color: ["#39FB00", "#4AABFF", "#F55300"],
    padding: [10, 10, 10, 10],
    dataLabel: true,
    enableScroll: false,
    legend: {
      show: false,
    },
    title: {},
    subtitle: {
      name: "",
    },
    extra: {
      ring: {
        ringWidth: 20, //圆环的宽度
        centerColor: "#ffffff", //中间填充圆形的颜色
        activeOpacity: 0.5, //启用Tooltip点击时，突出部分的透明度
        activeRadius: 8, //启用Tooltip点击时，突出部分的宽度
        offsetAngle: 0, //起始角度偏移度数，顺时针方向，
        labelWidth: 15, //数据标签到饼图外圆连线的长度
        border: false, //是否绘制各类别中间的分割线
      },
    },
  },
});
// 柱状图
const chartParam = reactive({
  opts: {
    animation: false, // 关闭动画
    update: true, // 关键：是否开启连续更新数据的方法,开启之后就不会抖动了
    duration: 0, // 关闭动画过度
    padding: [10, 0, 0, 0],
    enableScroll: false,
    legend: { show: false },
    dataLabel: false, // 不显示数据标签
    xAxis: {
      disableGrid: true, //不绘制纵向网格
      fontColor: "#000000", //字体颜色
      fontSize: 12, //字体大小
      axisLineColor: "#707070", //坐标轴轴线颜色
      marginTop: "5", //X轴文字距离轴线的距离
    },
    yAxis: {
      disableGrid: true, //不绘制横向向网格
      data: [
        {
          min: 0,
          calibration: true, //刻度线是否显示
          fontColor: "#8A8A8A", //字体颜色
          axisLineColor: "#707070", //坐标轴轴线颜色
        },
      ],
    },
    extra: {
      column: {
        type: "group",
        width: 10,
        linearType: "custom", //渐变类型
        customColor: ["#88C5EC", "#4299FE"],
        activeBgColor: "#000000", //当前点击柱状图的背景颜色
        activeBgOpacity: 0.08, //当前点击柱状图的背景颜色透明度
      },
    },
  },
  chartData: {},
});
// 服务评价统计
const getEvaluationStat = () => {
  evaluationStat(queryParam.value)
    .then((res: any) => {
      const { data } = res;
      // 饼状图数据
      renderPieChart(data);
      // 表格数据
      tableList.value = data.communityTableVos ?? [];

      // 年度统计柱状图数据
      if (queryParam.value.type == 1) {
        data.yearStatisticsVos = data.yearStatisticsVos ?? [];
        let xdata = <any>[];
        let ydata = <any>[];
        data.yearStatisticsVos = data.yearStatisticsVos ?? [];
        if (data.yearStatisticsVos.length) {
          data.yearStatisticsVos.forEach((item: any) => {
            xdata.push(item.month);
            ydata.push(item.monthCount - 0);
          });
        }
        let chartData = {
          categories: xdata,
          series: [
            {
              name: "评价次数",
              data: ydata,
            },
          ],
        };
        chartParam.chartData = JSON.parse(JSON.stringify(chartData));
      }
    })
    .catch((err: any) => {
      uToastRef.value.show({
        type: "error",
        message: err,
      });
    });
};
// 服务评价统计改变筛选条件
const updateEvaluationStat = (mode: number) => {
  queryParam.value.type = mode;
  if (mode == 0) {
    queryParam.value.yearMonth = dayjs(new Date()).format("YYYY-MM");
    timeStr.value = dayjs(new Date()).format("YYYY年MM月");
  } else {
    queryParam.value.yearMonth = dayjs(new Date()).format("YYYY");
    timeStr.value = dayjs(new Date()).format("YYYY年");
  }
  getEvaluationStat();
};
// 时间选择改变
const bindPickerChange = (e: any) => {
  if (e.detail.value.includes("-")) {
    queryParam.value.yearMonth =
      e.detail.value.split("-")[0] + "-" + e.detail.value.split("-")[1];
    timeStr.value =
      e.detail.value.split("-")[0] + "年" + e.detail.value.split("-")[1] + "月";
  } else {
    queryParam.value.yearMonth = e.detail.value;
    timeStr.value = e.detail.value + "年";
  }
  getEvaluationStat();
};
// 饼状图渲染统计
const renderPieChart = (data: any) => {
  let seriesData = {
    series: [
      {
        data: [
          {
            name: "满意",
            value: 0,
            labelText: `满意：0%`,
          },
          {
            name: "一般",
            value: 0,
            labelText: `一般：0%`,
          },
          {
            name: "不满意",
            value: 0,
            labelText: `不满意：0%`,
          },
        ],
      },
    ],
  };
  let title = {
    name: 0,
    fontSize: 25,
    color: "#000000",
  };
  // 饼状图数据
  if (data.sumCount > 0) {
    seriesData = {
      series: [
        {
          data: [
            {
              name: "满意",
              value: data.satisfiedCount - 0,
              labelText: `满意：${toFixedWithoutTrailingZeros(
                (data.satisfiedCount / (data.sumCount - 0)) * 100
              )}%`,
            },
            {
              name: "一般",
              value: data.generalCount - 0,
              labelText: `一般：${toFixedWithoutTrailingZeros(
                (data.generalCount / (data.sumCount - 0)) * 100
              )}%`,
            },
            {
              name: "不满意",
              value: data.dissatisfiedCount - 0,
              labelText: `不满意：${toFixedWithoutTrailingZeros(
                (data.dissatisfiedCount / (data.sumCount - 0)) * 100
              )}%`,
            },
          ],
        },
      ],
    };
    title = {
      name: data.sumCount - 0,
      fontSize: 25,
      color: "#000000",
    };
  }
  evaluationChart.chartData = JSON.parse(JSON.stringify(seriesData));
  evaluationChart.opts.title = JSON.parse(JSON.stringify(title));
};
// 查看服务评价详情
const scanDetail = (row: any) => {
  uni.navigateTo({
    url: `/subPages/leader/serviceEvaluation/detail?detailInfo=${JSON.stringify(
      row
    )}&type=${queryParam.value.type}&yearMonth=${queryParam.value.yearMonth}`,
  });
};

onMounted(() => {
  getEvaluationStat();
});
</script>

<style lang="scss" scoped>
.leader-report-complaint {
  .select-input {
    width: calc(100% - 84rpx - 84rpx - 24rpx);
    ::v-deep .u-input__content {
      border-radius: 14rpx !important;
      border: 0.7rpx solid #707070 !important;
    }
    ::v-deep .u-input__content__field-wrapper__field {
      padding: 0 22rpx;
      height: 50rpx !important;
    }
  }
  .ring-charts {
    width: 100%;
    height: 300rpx;
  }
  .bar-chart {
    width: 100%;
    height: 300rpx;
  }
  ::v-deep .uni-table {
    min-width: 0 !important;
  }
  ::v-deep .uni-table-th {
    padding: 12rpx 20rpx;
    font-size: 25rpx;
    font-weight: 400;
    color: #000000;
    // border-bottom: 0.7rpx #707070 solid;
    background: #e1eeff;
    border-top: 1px solid #ebeef5;
    border-left: 1px solid #ebeef5;
  }
  ::v-deep .uni-table-td {
    padding: 12rpx 20rpx;
    font-size: 25rpx;
    font-weight: 400;
    color: #000000;
  }
  //   ::v-deep .table--border {
  //     border-right: 0.7rpx #707070 solid;
  //   }
  //   ::v-deep .uni-table-tr {
  //     .table--border:last-child {
  //       border-right: none;
  //     }
  //   }
}
</style>
